using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;

public class SaveManager : MonoBehaviour
{
    public static SaveManager Instance;
    [SerializeField] private string fileName = "GameSaveData.json";
    [SerializeField] private bool isEncrpyData;
    private FileDataHandler fileDataHandler;
    private GameData gameData;

    private List<ISaveable> saveables = new();
    private void Awake()
    {
        Instance = this;
    }

    private IEnumerator Start()
    {
        fileDataHandler = new(Application.persistentDataPath, fileName, isEncrpyData);
        saveables = GetSaveableInGame();

        yield return null;
        LoadGame();
    }

    public void SaveGame()
    {
        foreach (var saveable in saveables)
            saveable.SaveData(ref gameData);
        fileDataHandler.SaveData(gameData);
        Debug.Log("保存游戏存档");
    }

    public void LoadGame()
    {
        gameData = fileDataHandler.LoadData();
        
        gameData ??= new();

        foreach (var saveable in saveables)
            saveable.LoadData(gameData);
        Debug.Log("加载游戏存档");
    }
    [ContextMenu("删除存档")]
    public void DeleteGame()
    {
        fileDataHandler = new(Application.persistentDataPath, fileName, isEncrpyData);
        fileDataHandler.DeleteData();

        // LoadGame();
    }
    private void OnApplicationQuit()
    {   
        SaveGame();
    }
    public GameData GetGameData() => gameData;
    private List<ISaveable> GetSaveableInGame() =>
            FindObjectsByType<MonoBehaviour>(FindObjectsInactive.Include, FindObjectsSortMode.None)
            .OfType<ISaveable>().ToList();
}
